// pages/allpicate/index.js
import {
  axFormValidator
} from "../../components/ax-validator";
import {
  transformFields,
  transformFormFields,
} from '../../utils/tools';
import {
  axios_base_post,
  axios_base_get
} from "../../utils/axios";
import {
  dataRegexp
} from '../../utils/tools';
const app = getApp()
Page({

  /**
   * 页面的初始数据
   */
  data: {
    proviceList: [], //省份
    businessIdList: [], //业务类型
    scoolList: [], //学校
    pointList: [], //代理点
    insurTypeList: [], //险种
    companyList: [], //保险公司
    coverageList: [], //理赔类型
    fileList: [],
    relationFileList: [], //关系证明
    bankFileList: [], //银行卡
    taskFlag: null, //业务类型
    zhutiFlag: null,
    company: null, //选中承保公司
    claimsType: null, //选中险种
    zhutiList: [{
      text: '机构',
      value: 1
    }, {
      text: '个人',
      value: 2
    }],
    fields: {
      regionId: {
        label: '所属省份',
        required: true,
        value: null,
      },
      businessId: {
        label: '业务类型',
        required: true,
        value: null,
      },
      schoolId: {
        label: '所属学校',
        required: true
      },
      saleType: {
        label: '销售主体',
        required: false
      },
      agentPointId: {
        label: '代理点',
        required: false,
        value: null
      },
      agentMember: {
        label: '代理人',
        required: false
      },
      companyId: {
        label: '承保公司',
        required: true,
        value: null
      },
      coverageId: {
        label: '险种',
        required: true,
        value: null
      },
      policyNumber: {
        label: '保单号',
        required: true
      },
      classId: {
        label: '理赔类型',
        required: true,
        value: null
      },
      insured: {
        label: '姓名',
        required: true
      },
      idcard: {
        label: '身份证号',
        required: true,
        // pattern: 'idcard',
      },
      insuredPhone: {
        label: '联系电话',
        required: true,
        pattern: 'mobile',
      },
      time: {
        label: '出险日期',
        required: true
      },
      describe: {
        label: '事件描述',
      },
      total: {
        label: '保额（万元）',
        pattern: 'baoE'
      },
      peiFuTotal: {
        label: '赔付金额（元）',
        pattern: 'peifu'
      },
      CardType: {
        label: '开户行',
      },
      OpenBank: {
        label: '开户网点',
      },

    },
    fieldsBind: {
      phone: {
        label: '绑定手机号码',
        pattern: 'mobile',
        required: true
      },
      code: {
        label: '验证码',
        required: true
      }
    },
    showPhoneVisible: false, //绑定手机号弹窗
    fieldlist: [],
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {},

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {},

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    this.getProviceList()
    this.getBusiness()
    this.getSchool()
    this.getCompany()
    this.getInsurTypeList()
    this.getCoverageList()
  },
  onTabItemTap: function (item) {
    const info = wx.getStorageSync('userInfoStorage')
    if (info.roleName == '游客') {
      this.setData({
        showPhoneVisible: true
      })
    }
  },
  //获取省份
  getProviceList() {
    axios_base_get('/Common/GetProvince', true).then((res) => {
      if (res.success) {
        this.setData({
          proviceList: res.data.result,
          'fields.regionId.value': res.data.result.find(item => item.value == 24).value
        })
      }
    })
  },
  //获取业务类型
  getBusiness() {
    axios_base_get('/Common/BusinessClassSelector', true).then((res) => {
      if (res.success) {
        this.setData({
          businessIdList: res.data,
        })
      }
    })
  },
  //获取学校
  getSchool() {
    axios_base_get('/Common/SchoolSelector', true).then((res) => {
      if (res.success) {
        this.setData({
          scoolList: res.data,
        })
      }
    })
  },
  //获取代理点
  getAgentPoint() {
    axios_base_get('/Common/AgentPointSelector', {
      businessId: this.data.taskFlag
    }, true).then((res) => {
      if (res.success) {
        this.setData({
          pointList: res.data,
        })
      }
    })
  },
  //获取保险公司
  getCompany() {
    axios_base_get('/Common/CompanySelector', true).then((res) => {
      if (res.success) {
        this.setData({
          companyList: res.data,
        })
      }
    })
  },
  //获取理赔类型
  getCoverageList() {
    axios_base_get('/Common/ClaimsClassSelector', true).then((res) => {
      if (res.success) {
        this.setData({
          coverageList: res.data,
        })
      }
    })
  },
  //获取险种
  getInsurTypeList() {
    axios_base_get('/Common/CoverageSelector', true).then((res) => {
      if (res.success) {
        this.setData({
          insurTypeList: res.data,
        })
      }
    })
  },
  //根绝业务类型和学校获取保险信息
  getInsurInfo(schoolId) {
    const params = {
      businessClassId: this.data.taskFlag,
      schoolId
    }
    axios_base_get('/Common/GetBaseInfoById', {
      ...params
    }, true).then((res) => {
      if (res.success && res.data) {
        this.setData({
          'fields.companyId.value': res.data.companyId || null,
          'fields.coverageId.value': res.data.coverageId || null,
          'fields.policyNumber.value': res.data.policyNumber || null,
          'fields.classId.value': res.data.classId || null,
        })
        //保险公司和险种存在的情况，获取
        if (res.data.companyId && res.data.coverageId) {
          this.getExtendInfo()
        }
      }
    })
  },
  //获取理赔资料
  getExtendInfo() {
    this.data.fieldlist = []
    const params = {
      companyId: this.data.company,
      coverageId: this.data.claimsType
    }
    axios_base_get('/Common/GetExtendInfo', {
      ...params
    }, true).then((res) => {
      if (res.success && res.data) {
        res.data.map(item => {
          item.list = transformFormFields(item.extendFields)
          item.field = transformFields(item.extendFields, item.groupName, item.groupId)
        })
        this.setData({
          fieldlist: res.data
        })
      }
    })
  },
  //业务类型变化
  taskChange(e) {
    const value = e.detail.value.value
    this.setData({
      taskFlag: value
    })
    this.setData({
      'fields.saleType.required': value == 1 ? false : true,
      'fields.agentPointId.required': value == 1 ? false : true,
    })
    this.getAgentPoint()
  },
  //销售主体变化
  zhutiChange(e) {
    this.setData({
      zhutiFlag: e.detail.value.value
    })
    if (e.detail.value.value == 2) {
      this.setData({
        'fields.agentMember.required': e.detail.value.value == 2 ? true : false
      })
    }
  },
  //学校变化
  schoolChange(e) {
    this.getInsurInfo(e.detail.value.value)
  },
  //承保公司变化
  companyChange(e) {
    this.setData({
      company: e.detail.value.value
    })
    if (e.detail.value.value && this.data.claimsType) {
      this.getExtendInfo()
    }
  },
  //险种变化
  coverageChange(e) {
    this.setData({
      claimsType: e.detail.value.value
    })
    if (e.detail.value.value && this.data.company) {
      this.getExtendInfo()
    }

  },
  fatherFileData(e) {
    //给之前组装的fieldlist对应的数据赋值，只针对于图片和文档的时候
    const selfData = this.data.fieldlist
    selfData.map((item, index) => {
      for (let key in item.field) {
        let m = item.field[key]
        //判断返回的对象中是否有fileImageList字段
        let n = e.detail[key]?.hasOwnProperty('fileImageList')
        if ((m.boxType == 10 || m.boxType == 11) && n) {
          //当为图片或文档上传时才赋值
          m.fileImageList = e.detail[key].fileImageList
          m.errorMessage = e.detail[key].errorMessage
        }
      }
    })
    this.setData({
      fieldlist: selfData
    })
  },
  toSure: function (e) {
    let data = this.data.fields
    let fieldlist = this.data.fieldlist
    //循环遍历给form表单对应的上传字段赋值
    fieldlist.map((item, index) => {
      for (let key in item.field) {
        let a = item.field[key]
        let b = a.boxType == 10 || a.boxType == 11
        let n = a?.hasOwnProperty('fileImageList')
        data[a.label] = {
          label: a.label,
          value: null,
          required: a.isRequired
        }
        if (b && n) {
          e.detail.value[a.label] = a.fileImageList
        }
      }
    })
    this.setData({
      fields: data
    })
    const {
      fields,
    } = this.data
    const req = e.detail.value
    axFormValidator(fields, req).then((res) => {
      //租组装提交数据格式
      let fortmatData = this.data.fieldlist
      fortmatData.map((m, n) => {
        for (let k in m.field) {
          m.field[k].value = req[m.field[k].label]
          m.extendFields = []
          m.extendFields.push(m.field[k])
        }
      })
      req.extendGroup = JSON.stringify(fortmatData)
      this.save(req)
    }).catch((res) => {
      let dataBefore = this.data.fieldlist
      //给自定义字段数据赋值errorMessage
      dataBefore.map((item, index) => {
        for (let key in item.field) {
          let a = item.field[key]
          let b = this.data.fields[a.label] //判断表单所有数据是否包含自定义的那个字段
          if (b) {
            a.errorMessage = this.data.fields[a.label].errorMessage
          }
        }
      })
      this.setData({
        fieldlist: dataBefore
      })
      let arr = []
      for (let i in res) {
        if (res[i].required && res[i].errorMessage !== '') {
          arr.push(res[i].label)
        }
      }
      this.setData({
        fields: res
      })
      if (arr.length !== 0) {
        wx.showModal({
          title: '提示',
          content: `${[...arr]}不能为空,请先填写完整！`,
        })
      }
    })
  },
  save(req) {
    axios_base_post('/LeiPeiRequest/LeiPeiRequest', {
      ...req,
    }).then((res) => {
      if (res.data == true) {
        console.log('成功');
        // wx.navigateTo({
        //   url: "/pages/center/Set/feedBackSuccess/index",
        // })
      }
    })
  },
  /**输入手机号 */
  changePhone: function (e) {
    app.globalData.phone = e.detail
    this.setData({
      'fieldsBind.phone.value': e.detail
    })
  },
  /**获取验证码 */
  toGetCode: function () {
    if (this.data.fieldsBind.phone.value) {
      dataRegexp(this.data.fieldsBind.phone.value, 'mobile').then(res => {
        if (res == true) {
          axios_base_post('/UserResource/SendMobileCode', {
            mobile: this.data.fieldsBind.phone.value
          }, false).then(res => {
            if (res.success == true) {
              wx.showToast({
                title: '短信验证码已发送，请注意查收！',
                icon: 'none'
              })
            } else {
              wx.showToast({
                title: res.data.message,
                icon: 'none'
              })
            }
          })
        } else {
          wx.showToast({
            title: '请输入正确的手机号！',
            icon: 'none'
          })
        }
      })
    } else {
      wx.showToast({
        title: '请先输入手机号码！',
        icon: 'none'
      })
    }
  },
  inputCode(e) {
    this.setData({
      'fieldsBind.code.value': e.detail.value
    })
  },
  /**关闭绑定收集弹框 */
  onClosePhone: function () {
    this.setData({
      showPhoneVisible: false,
      'fieldsBind.phone.value': '',
      'fieldsBind.code.value': ''
    })
  },
  /**确认绑定 */
  toBindPhone: function (e) {
    const _self = this
    const {
      fieldsBind
    } = _self.data
    const req = e.detail.value;
    axFormValidator(fieldsBind, req).then((res) => {
      this.toSureBind()
      this.setData({
        fieldsBind,
        showPhoneVisible: false,
      })
    }).catch((res) => {
      this.setData({
        fieldsBind
      })
    })
  },
  toSureBind: function () {
    axios_base_post('/MemberManagement/Member/BindMoblie', {
      mobile: this.data.fieldsBind.phone.value,
      code: this.data.fieldsBind.code.value,
      userId: wx.getStorageSync('userInfoStorage').userId
    }, false).then(res => {
      if (res.success === true) {
        wx.showToast({
          title: '绑定成功',
          icon: 'none'
        })
        wx.clearStorage();
        this.setData({
          showPhoneVisible: false
        })
      }
    }).catch(err => {
      this.setData({
        showPhoneVisible: true,
      })
    })
  },
  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})